<template>
  <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
    <template #operator>
      <tableForm @handle-search="formSearch" ref="tableFormRef" />
      <div style="margin-top: 16px">
        <a-button type="primary" @click="addNewProject">
          <PlusOutlined />
          新增项目
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'projectType'"> {{ record.projectTypeName }} </template>
      <template v-if="column.dataIndex === 'status'"> {{ ProjectManagemenType[record.status].label }} </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelDetial(record)">详情</a>
          <a @click="handelEdit(record)">编辑</a>
          <a @click="handelDelete(record)">删除</a>
        </div>
      </template>
    </template>
  </Table>

  <BasicModal
    ref="showActionModal"
    :title="`${ModalName[showType]}-项目`"
    width="1000px"
    @emit-callback-fn="modalCallbackFn($event)"
    :confirmLoading="editPrijectLoading"
  >
    <template #content> <SchemaForm ref="formRef" /></template>
  </BasicModal>
</template>

<script lang="ts" setup>
import tableForm from './tableForm.vue';
import {
  getProjectManagementPage,
  getProjectTypeList,
  getUserList,
  addProjectData,
  putProjectData,
  deleteProjectData,
} from '@/api/projectManagement';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { ProjectManagemenStatus, ProjectManagemenType } from '@/enums/projectManagemenEnum';
import { ModalName, ModalType } from '@/enums/commonEnum';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import { useGlobal } from '@/store/modules';

const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'projectCode', title: '项目编号', align: 'center', ellipsis: true, width: 180 },
  { dataIndex: 'projectName', title: '项目名称', align: 'center', ellipsis: true },
  { dataIndex: 'status', title: '状态', align: 'center', ellipsis: true },
  { dataIndex: 'projectLeader', title: '项目负责人', align: 'center', ellipsis: true },
  { dataIndex: 'projectType', title: '项目类型', align: 'center', ellipsis: true },
  { dataIndex: 'creator', title: '创建人', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '创建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];
const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'projectCode',
      label: '项目编号',
      labelWidth: 100,
      colProps: {
        span: 12,
      },
      required: true,
      dynamicDisabled: () => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },
    {
      field: 'projectName',
      label: '项目名称',
      labelWidth: 100,
      colProps: {
        span: 12,
      },
      required: true,
      dynamicDisabled: () => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },

    {
      field: 'projectType',
      label: '项目类型',
      labelWidth: 100,
      required: true,
      colProps: {
        span: 12,
      },
      componentProps: {
        api: getProjectTypeList,
        placeholder: '请选择项目类型',
        showSearch: true,
        optionFilterProp: 'name',
        fieldNames: { label: 'name', value: 'id' },
      },
      dynamicDisabled: () => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'ApiSelect',
    },
    {
      field: 'projectLeader',
      label: '项目负责人',
      labelWidth: 100,
      required: true,
      colProps: {
        span: 12,
      },
      componentProps: {
        api: getUserList,
        placeholder: '请选择项目负责人',
        showSearch: true,
        optionFilterProp: 'realName',
        fieldNames: { label: 'realName', value: 'userId' },
      },
      dynamicDisabled: () => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'ApiSelect',
    },
    {
      field: 'status',
      label: '项目状态',
      labelWidth: 100,
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: {
        options: ProjectManagemenType,
        placeholder: '请选择项目状态',
      },
      vIf: ({}) => {
        return [ModalType.detail, ModalType.edit].includes(showType.value);
      },
      dynamicDisabled: () => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'Select',
    },
    {
      field: 'projectDescription',
      label: '项目描述',
      labelWidth: 100,
      colProps: {
        span: 24,
      },
      dynamicDisabled: () => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'InputTextArea',
    },
  ] as FormSchema[],
});
const global = useGlobal();
const showType = ref<ModalType>(ModalType.add);
const tableRef = ref<any>(null);
const showActionModal = ref<any>(null);
const listStatus = ref<ProjectManagemenStatus>(ProjectManagemenStatus.allProjects);
const fromSearchData = reactive({
  projectCode: '',
  projectName: '',
  projectType: undefined,
  projectLeader: undefined,
  startTime: '',
  endTime: '',
});

// table搜索事件
const formSearch = (from: any) => {
  delete from.lastRunTime;
  fromSearchData.projectCode = from.projectCode;
  fromSearchData.projectName = from.projectName;
  fromSearchData.projectType = from.projectType;
  fromSearchData.projectLeader = from.projectLeader;
  fromSearchData.startTime = from.startTime;
  fromSearchData.endTime = from.endTime;
  tableRef.value.refresh(true);
};

// 新建项目
const addNewProject = () => {
  showType.value = ModalType.add;
  showActionModal.value.showModal();
};

const editPrijectLoading = ref<boolean>(false);
const modalCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  if (showType.value == ModalType.add) {
    editPrijectLoading.value = true;
    await addProjectData(data)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
        global.fetchProject();
      })
      .finally(() => {
        editPrijectLoading.value = false;
      });
  }
  if (showType.value == ModalType.edit) {
    editPrijectLoading.value = true;
    let putData = {
      ...data,
      id: obj.propsData.id,
    };
    await putProjectData(putData)
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editPrijectLoading.value = false;
      });
  }
};

const handelDetial = async (record: any) => {
  nextTick(() => {
    formRef.setFieldsValue(record);
  });
  showType.value = ModalType.detail;
  showActionModal.value.showModal(record, '关闭');
};

//表格编辑
const handelEdit = async (record: any) => {
  nextTick(() => {
    formRef.setFieldsValue(record);
  });
  showType.value = ModalType.edit;
  showActionModal.value.showModal(record);
};

const refreshSelect = () => {
  tableFormRef.value.getNewData();
};

const handelDelete = (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode(
      'div',
      { style: 'color:black;' },
      `确定要删除“项目编码：${record.projectCode}，项目名称：${record.projectName}”这一项数据吗？`,
    ),
    async onOk() {
      await deleteProjectData(record.id).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
        global.fetchProject();
      });
    },
    onCancel() {},
  });
};

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: { ...fromSearchData, status: listStatus.value },
  };
  const data = await getList(parameObj);
  return data;
};
//获取表格数据
const getList = async (parameObj: any) => {
  return await getProjectManagementPage(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res?.records || [],
    };
    return data;
  });
};

// 刷新当前列表
const tableFormRef = ref<any>(null);
const refreshTable = (key?: string) => {
  listStatus.value = key as ProjectManagemenStatus;
  tableFormRef.value.resetData();
};

defineExpose({
  refreshTable,
  refreshSelect,
});
</script>

<style scoped lang="less">
.pipeline-name {
  display: flex;
  flex-direction: column;
  .pipeline-top-box {
    gap: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 4px;
    flex-wrap: wrap;
    .grouping-box {
      border-radius: 4px;
      display: inline-block;
      font-size: 12px;
      font-weight: 400;
      padding: 0 12px;
    }
  }
}
.running-status {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-operation {
  display: flex;
  justify-content: center;
  align-items: center;
}

.dropdown-item {
  display: flex;
  align-items: center;
  padding: 0 12px;
  .iconDef {
    margin-right: 8px;
  }
}

:deep(.ant-dropdown-menu-item:hover, .ant-dropdown-menu-submenu-title:hover) {
  background: rgba(37, 144, 255, 0.1);
  color: #1890ff;
}
.batch-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
